package cn.wawi.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import com.fasterxml.jackson.databind.ObjectMapper;
import sun.misc.BASE64Encoder;

/**
 * httpClient工具类
 * @author 龚亮
 */
public class HttpClientUtil {
	private static CloseableHttpClient httpClient;
	//设置超时时间,连接时间
    private static final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
	private static final String baseUrl="http://117.135.196.139:10032/udp-ebusiness/app/";
	
	public static void main(String[] args) throws Exception {
//		Map<String, Object> param=new HashMap<String, Object>();
//		param.put("terminal_id", "18602517465");
//		param.put("platform", "jiangsu");
//		param.put("member_id", "");
//		ObjectMapper mapper = new ObjectMapper();
//		System.out.println(mapper.writeValueAsString(param));
//		System.out.println(post(param,"user_detail.app"));
	//	System.out.println(xml());
	//	System.out.println(StringEscapeUtil.base64encode(StringEscapeUtil.md5("as")));
	}

	/**
	 * 
	 * @param phone 手机号
	 * @param num   金额
	 */
	public static String xml() throws JSONException{
	   	String result="";

        // 创建默认的httpClient实例.    
    	httpClient = HttpClients.createDefault();  
        // 创建httppost    
        HttpPost httpPost = new HttpPost("http://222.247.54.19:10030/gzticket/ticket.html");  
        httpPost.setConfig(requestConfig); 
        CloseableHttpResponse response=null;
        try {  
        	StringBuilder sb=new StringBuilder();
        	sb.append("<MPAY><HEAD>");
        	sb.append("<MCODE>101825</MCODE>");
        	sb.append("<CAPTCHA>SEDF345</CAPTCHA>");
        	sb.append("<MSGPRO>SF</MSGPRO>");
        	sb.append("<VER>0001</VER>");
        	sb.append("<REQSYS>HSH19880</REQSYS>");
        	sb.append("<SCH>rq</SCH>");
        	sb.append("<MSGATR>00</MSGATR>");
        	sb.append("<SAFEFLG>21</SAFEFLG>");
        	sb.append("</HEAD>");
        	sb.append("<BODY>");
        	sb.append("<CHANNEL_TRADE_ID>4221811999081201</CHANNEL_TRADE_ID>");
        	sb.append("<BUS_TYP>11</BUS_TYP>");
        	sb.append("<ACT_ID>1510130002</ACT_ID>");
        	sb.append("<PRD_ID></PRD_ID>");
        	sb.append("<CCPASSWD>111111</CCPASSWD>");
        	sb.append("</BODY></MPAY>");
        	System.out.println(sb.toString());
        	StringEntity  uefEntity = new StringEntity (sb.toString(),"GBK");  
        	httpPost.addHeader("Content-Type", "text/xml");
        	httpPost.setEntity(uefEntity);  
            System.out.println("executing request " + httpPost.getURI()); 
            response = httpClient.execute(httpPost);  
            HttpEntity entity = response.getEntity();  
            int statusCode = response.getStatusLine().getStatusCode();
            // 判断是够请求成功
            if (statusCode == HttpStatus.SC_OK) {
                // 获取返回的数据
               if(entity!=null) result = EntityUtils.toString(response.getEntity(), "GBK");
            } else {
                System.out.println("HttpPost xml方式请求失败!");
            }
        } catch (Exception e) {  
            e.printStackTrace();   
        } finally {  
            // 关闭连接,释放资源    
            close(httpClient,response); 
        }  
        return result;
	}
    /** 
     * post方式提交表单
     */  
    public static String post(Map<String, Object> param,String method) {  
    	String result="{}";
        // 创建默认的httpClient实例.    
    	httpClient = HttpClients.createDefault();  
        // 创建httppost    
        HttpPost httpPost = new HttpPost(baseUrl+method);  
        httpPost.setConfig(requestConfig); 
        CloseableHttpResponse response=null;
        try {  
        	ObjectMapper mapper = new ObjectMapper();
    		List<BasicNameValuePair> paramMap = new ArrayList<BasicNameValuePair>();
    		String jsonParam = encryptBASE64(mapper.writeValueAsString(param));
    		paramMap.add(new BasicNameValuePair("reqparam", jsonParam));
        	UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(paramMap, "UTF-8");  
            httpPost.setEntity(uefEntity);  
            System.out.println("executing request " + httpPost.getURI()); 
            response = httpClient.execute(httpPost);  
            HttpEntity entity = response.getEntity();  
            int statusCode = response.getStatusLine().getStatusCode();
            // 判断是够请求成功
            if (statusCode == HttpStatus.SC_OK) {
                // 获取返回的数据
               if(entity!=null) result = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                System.out.println("HttpGet方式请求失败!");
            }
        } catch (Exception e) {  
            e.printStackTrace();   
        } finally {  
            // 关闭连接,释放资源    
            close(httpClient,response); 
        }  
        return result;
    }  
  
    /** 
     * 发送 get请求
     */  
    public static String get(String method) {  
    	String result="";
        // 创建默认的httpClient实例.    
    	httpClient = HttpClients.createDefault();  
    	CloseableHttpResponse response=null;
        HttpGet httpGet = new HttpGet(baseUrl+method);//发送GET请求
        httpGet.setConfig(requestConfig);
        //formparams.add(new BasicNameValuePair("username", "admin"));  
        try {  
        	response=httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            // 判断是够请求成功
            if (statusCode == HttpStatus.SC_OK) {
                // 获取返回的数据
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                System.out.println("HttpGet方式请求失败!");
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            close(httpClient,response);
        }  
        return result;
    }  
    //解析Map转为HttpClient请求参数 base64加密
	public static String encryptBASE64(String key) throws IOException {
		String code = new BASE64Encoder().encode(key.getBytes("UTF-8"));
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(code);
		return m.replaceAll("");
	}
    public static void close(CloseableHttpClient httpClient,CloseableHttpResponse response){
        // 关闭连接,释放资源    
        try {  
            httpClient.close();  
            response.close();
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }
}
